package com.hqu.jim.controller;

import com.hqu.jim.entity.Attendance;
import com.hqu.jim.service.AttendanceService;
import com.hqu.jim.service.impl.AttendanceServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

@WebServlet(urlPatterns = {"/Attendance/getTop","/Attendance/getLeft","/Attendance/getAttendance","/Attendance/updateScore"})
public class AttendanceServlet extends HttpServlet {

    private AttendanceService attendanceService;

    @Override
    public void init() throws ServletException {
        attendanceService = new AttendanceServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的URI地址信息
        String url = req.getRequestURI();
        // 截取其中的方法名
        String methodName = url.substring(url.lastIndexOf("/")+1);
        Method method = null;
        try {
            // 使用反射机制获取在本类中声明了的方法
            method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 执行方法
            method.invoke(this, req, resp);
        } catch (Exception e) {
            throw new RuntimeException("调用方法出错！");
        }
    }

    protected void getTop(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
        //req.setAttribute("username",req.getSession().getAttribute("username"));
        req.getRequestDispatcher("/top.jsp").forward(req,resp);
    }

    protected void getLeft(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
        req.getRequestDispatcher("/left.jsp").forward(req,resp);
    }

    protected void getAttendance(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
        String fileName = req.getParameter("fileName");
        req.getSession().setAttribute("fileName",fileName);
        List<Attendance> attendances = attendanceService.getAllUser(fileName);
        req.setAttribute("attendances",attendances);
        req.getRequestDispatcher("/attendance.jsp").forward(req,resp);
    }

    protected void updateScore(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
        String fileName = (String)req.getSession().getAttribute("fileName");
        String score = (String)req.getParameter("score");      //分数
        String sequence = (String)req.getParameter("sequence");//学号
        attendanceService.updateUserByUserSequence(fileName,sequence,score);
    }
}
